home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8321 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  60 lines

  1. Newsgroups: comp.lang.c
  2. Path: nntp.coast.net!torn!info!rede4740
  3. From: rede4740@mach1.wlu.ca (Chris Redekop u)
  4. Subject: Q:  gets, getch, and stdin
  5. X-Newsreader: TIN [version 1.1 PL6]
  6. Message-ID: <DnoC9w.Eq9@info.uucp>
  7. Nntp-Posting-Host: mach1.wlu.ca
  8. Sender: news@info.uucp (news management)
  9. Organization: Wilfrid Laurier University
  10. Date: Sun, 3 Mar 1996 04:25:07 GMT
  11.  
  12.  
  13. Hi.  I'm trying to teach myself C with the help of 'Teach Yourself C In 
  14. 21 Days'.  Everything was going fine until day 14, 'Working with the 
  15. Screen, Printer, and Keyboard'.  On page 319 (in case anyone reading this 
  16. has the book), it talked about how using scanf can leave unwanted 
  17. characters in stdin.  It offered this function as a way to clear stdin:
  18.  
  19. void clear_kb(void)
  20. {
  21. char junk[80];
  22. gets(junk);
  23. }
  24.  
  25. I thought to myself, 'That might work, but it uses a whole array to do 
  26. it.  Instead of clearing stdin by reading a whole string, I should be 
  27. able to clear it one chartacter at a time, by using getch().  Then I 
  28. would only need one local variable of type char (or int).'  So I tried this:
  29.  
  30. void clear_kb(void)
  31. {
  32. char ch;
  33.  
  34. while ((ch = getch()) != '\r')
  35.     ;
  36. }
  37.  
  38. This didn't work, so after I tried a few different things, I found that 
  39. this works:
  40.  
  41. void clear_kb(void)
  42. {
  43. char ch;
  44.  
  45. while ((ch = getchar()) != '\n')
  46.     ;
  47. }
  48.  
  49. This is what confuses me.  I can't understand why the third function 
  50. works, and not the second.  As well, the third function does not output 
  51. the cleared characters to the screen, even though getchar provides input 
  52. with echo.  I think this all has something to do with (what is to me) the 
  53. mysterious nature of stdin.  Unfortunately, this was not as clearly 
  54. covered in the book as I needed.  If anyone can shed some light on this 
  55. elementary subject I would very much aprreciate it.
  56.  
  57. Thank you,
  58. Chris Redekop 
  59.  
  60.